from django.shortcuts import render,redirect
from df_user.models import UserInfo
from df_goods.models import GoodsInfo
from df_cart.models import CartInfo
from df_order.models import OrderInfo,OrderDetailInfo
from datetime import datetime
from decimal import Decimal
from django.http import JsonResponse
from df_user import user_decorator
#事务
from django.db import transaction
# Create your views here.

def order(request):
    #查询用户对象
    user = UserInfo.objects.get(id=request.session.get('user_id'))
    #根据提交查询购物车
    get = request.GET
    #得到购物车列表(得到的是字符串,要转换成int型)
    cart_ids = get.getlist('cart_id')
    #转换成int型
    cart_ids=[int(item) for item in cart_ids]
    #创建所有购物车对象
    carts = []
    for i in cart_ids:
        # print(i)
        cart = CartInfo.objects.get(id=i)
        carts.append(cart)
    
    context={
        'title':'提交订单',
        'page_name':1,
        'carts':carts,
        'user':user,
        
    }
    return render(request, 'df_order/place_order.html', context)

'''
事务:一旦操作全部回退
1.创建订单对象
2.判断商品的库存
3.创建订单对象
4.修改商品库存
5.删除购物车
'''

@transaction.atomic()
@user_decorator.login
def order_handle(request):
    #创建一个记录点,便于回退
    tran_id = transaction.savepoint()
    cart_ids = request.POST.getlist('cart_ids[]')
    print(cart_ids)
    try:
        #创建订单对象
        order = OrderInfo()
        now = datetime.now()
        uid = request.session['user_id']
        order.oid =request.POST.get('id')
        order.user_id = uid
        order.odate = now
        order.ototal = Decimal(request.POST.get('total'))
        order.oaddress = request.POST.get('address')
        order.save()
       
        # 创建祥单对象
        cart_ids1 = [int(item) for item in cart_ids]
        print(cart_ids1)
        for id1 in cart_ids1:
             detail = OrderDetailInfo()
             detail.order = order
             #查询购物车信息
             cart = CartInfo.objects.get(id=id1)
             #判断商品库存
             goods = cart.goods
             if goods.gkucun >= cart.count: #如果库存大于购买的数量
                 #减少商品库存
                 goods.gkucun=cart.goods.gkucun-cart.count
                 goods.save()
                 #完善祥单信息
                 detail.goods_id = goods.id
                 detail.price = goods.gprice
                 detail.count  = cart.count
                 detail.save()
                 #删除购物车数据
                 cart.delete()
             else:#如果库存小于购买数量
                 transaction.savepoint_rollback(tran_id)
                 return JsonResponse({'status': 2})
        transaction.savepoint_commit(tran_id)
    except Exception as e:
        print('=================='+str(e))
        transaction.savepoint_rollback(tran_id)
        
    return JsonResponse({'status': 1})



def pay(request, order_id):
    #这里表示已经支付了
    order = OrderInfo.objects.get(oid=order_id)
    order.oIsPay = True
    order.save()
    context = {
        'order_id':order_id
    }
    return render(request, 'df_order/pay.html', context)
